package dao.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.logging.Level;
import java.util.logging.Logger;

import dao.mysql.util.MySQLUtility;

public abstract class BaseDAO {
	private Connection conn;
	
	protected Connection getConnection() {
		return conn;
	}
	
	public BaseDAO() {
		conn = null;
	}
	
	protected void openConnection() {
		openConnection(true);
	}
	
	protected void openConnection(boolean autoCommit) {
		try {
			conn = MySQLUtility.getConnection();
			conn.setAutoCommit(autoCommit);
		} catch (SQLException | ClassNotFoundException e) {
			String error = "Error in Opening Connection. Nested Exception is: " + e;
			printLog(error, Level.SEVERE);
		}
	}
	
	protected Statement getStatement() throws SQLException {
		return conn.createStatement();
	}
	
	protected PreparedStatement getPreparedStatement(String sql) throws SQLException {
		return conn.prepareStatement(sql);
	}
	
	protected void commit() {
		try {
			conn.commit();
		} catch (SQLException e) {
			String error = "Error in Commit Transaction. Nested Exception is: " + e;
			printLog(error, Level.SEVERE);
		}
	}
	
	protected void closeConnection() {
		try{
			conn.rollback();
		} catch (Exception e) {
			String error = "Error in Closing Connection. Nested Exception is: " + e;
			printLog(error, Level.SEVERE);
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void printLog(String error, Level level) {
		Logger.getLogger(getClass().getName()).log(level, error);
	}
}
